<template>
  <BasicPanel v-if="showPanel">
    <a-tab-pane key="2" :tab="t('外部流程')">
      <FormItem :label="t('流程模板：')">
        <SelectDesign
          :single="true"
          :list="[{ id: formInfo.schemaId, code: formInfo.code, name: formInfo.schemaName }]"
          @change="selectDesign"
        >
          <InputModel :value="formInfo.schemaName" :placeholder="t('点击选择外部流程模板')" />
        </SelectDesign>
      </FormItem>

      <FormItem :label="t('调用类型：')">
        <a-select
          v-model:value="formInfo.callActivityType"
          :placeholder="t('请选择调用类型')"
          style="width: 100%"
          @change="changeCallActivityType"
        >
          <a-select-option :value="CallActivityType.SINGLE">{{ t('单实例') }}</a-select-option>
          <a-select-option :value="CallActivityType.MULTIPLE">{{ t('多实例') }}</a-select-option>
        </a-select>
      </FormItem>

      <!-- 单实例 -->
      <FormItem :label="t('发起人：')" v-if="formInfo.callActivityType === CallActivityType.SINGLE">
        <a-select
          v-model:value="formInfo.originatorNode"
          :placeholder="t('请选择发起人')"
          style="width: 100%"
        >
          <a-select-option v-for="item in configInfo.nodeList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </FormItem>

      <!-- 多实例 -->
      <template v-if="formInfo.callActivityType === CallActivityType.MULTIPLE">
        <FormItem :label="t('执行类型：')">
          <a-select
            v-model:value="formInfo.executionType"
            :placeholder="t('请选择执行类型')"
            style="width: 100%"
            @change="updateCallActivityXml"
          >
            <a-select-option :value="ExecutionType.SEQUENCE">{{ t('顺序执行') }}</a-select-option>
            <a-select-option :value="ExecutionType.PARALLEL">{{ t('并行执行') }}</a-select-option>
          </a-select>
        </FormItem>
        <FormItem :label="t('完成条件：')">
          <a-select
            v-model:value="formInfo.finishType"
            :placeholder="t('请选择执行类型')"
            @change="finishTypeChange"
            style="width: 100%"
          >
            <a-select-option :value="FinishType.ALL">{{ t('全部') }}</a-select-option>
            <a-select-option :value="FinishType.SINGLE">{{ t('单个') }}</a-select-option>
            <a-select-option :value="FinishType.PERCENTAGE">{{ t('百分比') }}</a-select-option>
          </a-select>
        </FormItem>
        <FormItem :label="t('百分比：')" v-if="formInfo.finishType == FinishType.PERCENTAGE">
          <a-input-number
            :min="1"
            :max="100"
            @change="percentChange"
            v-model:value="formInfo.percentOf"
            style="width: 100%"
          />
        </FormItem>
        <FormItem :label="t('发起人类型：')">
          <a-select
            v-model:value="formInfo.originatorType"
            :placeholder="t('请选择执行类型')"
            style="width: 100%"
          >
            <a-select-option :value="MemberType.FORM_FIELD">{{ t('表单数据') }}</a-select-option>
          </a-select>
        </FormItem>
        <FormItem :label="t('发起人配置：')">
          <div v-if="formInfo.originatorType == MemberType.FORM_FIELD">
            <a-tree-select
              v-model:value="formInfo.originatorConfig"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :placeholder="t('请选择发起人配置')"
              tree-default-expand-all
              :tree-data="configInfo.dataOfVariables"
              :field-names="{
                children: 'children',
                label: 'title',
                value: 'key',
              }"
              @select="selectDataOfVariables"
            />
          </div>
        </FormItem>
      </template>

      <!-- 输入 输出参数 -->

      <a-tabs>
        <a-tab-pane key="1" :tab="t('输入参数')">
          <div class="opr-box">
            <NodeHead :nodeName="t('参数传输')" />
            <div class="button-box">
              <a-button type="primary" @click="addInParamsItem">{{ t('添加') }}</a-button>
            </div>
          </div>
          <div class="list">
            <div class="row head">
              <span class="common">{{ t('变量来源（主流程）') }}</span>
              <span class="common">{{ t('目标变量（子流程）') }}</span>
              <span class="small">{{ t('操作') }}</span>
            </div>
            <div class="body" v-if="formInfo.inParams.length > 0">
              <div class="row item" v-for="(item, index) in formInfo.inParams" :key="index">
                <span class="common">
                  <a-tree-select
                    v-model:value="item.source"
                    show-search
                    style="width: 100%"
                    :placeholder="t('请选择')"
                    allow-clear
                    tree-default-expand-all
                    :tree-data="configInfo.mainSourceList"
                    :field-names="{
                      children: 'children',
                      label: 'title',
                      value: 'key',
                    }"
                /></span>
                <span class="common">
                  <a-tree-select
                    v-model:value="item.target"
                    show-search
                    style="width: 100%"
                    :placeholder="t('请选择')"
                    allow-clear
                    tree-default-expand-all
                    :tree-data="configInfo.targetList"
                    :field-names="{
                      children: 'children',
                      label: 'title',
                      value: 'key',
                    }"
                /></span>
                <span @click="deleteInParamsItem(index)" class="small">
                  <Icon icon="ant-design:delete-outlined" class="delete-icon" />
                </span>
              </div>
            </div>
            <EmptyBox v-else :has-icon="false" />
          </div>
        </a-tab-pane>
        <a-tab-pane
          key="2"
          :tab="t('输出参数')"
          v-if="formInfo.callActivityType === CallActivityType.SINGLE"
        >
          <div class="opr-box">
            <NodeHead :nodeName="t('参数传输')" />
            <div class="button-box">
              <a-button type="primary" @click="addOutParamsItem">{{ t('添加') }}</a-button>
            </div>
          </div>
          <div class="list">
            <div class="row head">
              <span class="common">{{ t('变量来源（子流程）') }}</span>
              <span class="common">{{ t('目标变量（主流程）') }}</span>
              <span class="small">{{ t('操作') }}</span>
            </div>
            <div class="body" v-if="formInfo.outParams.length > 0">
              <div class="row item" v-for="(item, index) in formInfo.outParams" :key="index">
                <span class="common">
                  <a-tree-select
                    v-model:value="item.source"
                    show-search
                    style="width: 100%"
                    :placeholder="t('请选择')"
                    allow-clear
                    tree-default-expand-all
                    :tree-data="configInfo.targetList"
                    :field-names="{
                      children: 'children',
                      label: 'title',
                      value: 'key',
                    }"
                /></span>
                <span class="common">
                  <a-tree-select
                    v-model:value="item.target"
                    show-search
                    style="width: 100%"
                    :placeholder="t('请选择')"
                    allow-clear
                    tree-default-expand-all
                    :tree-data="configInfo.sourceList"
                    :field-names="{
                      children: 'children',
                      label: 'title',
                      value: 'key',
                    }"
                /></span>

                <span @click="deleteOutParamsItem(index)" class="small">
                  <Icon icon="ant-design:delete-outlined" class="delete-icon" />
                </span>
              </div>
            </div>
            <EmptyBox v-else :has-icon="false" />
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-tab-pane>
  </BasicPanel>
</template>

<script setup lang="ts">
  import { inject, onMounted, reactive } from 'vue';
  import useStateFormInfo from '/@bpmn/hooks/useStateFormInfo';
  import { NodesConfig } from '/@/model/workflow/memberSetting';
  import BasicPanel from '/@bpmn/components/BasicPanel.vue';
  import SelectDesign from '/@bpmn/components/design/SelectDesign.vue';

  import { NodeHead, EmptyBox } from '/@/components/ModalPanel/index';
  import Icon from '/@/components/Icon/index';
  import InputModel from '/@bpmn/components/InputModel.vue';
  import FormItem from '/@bpmn/layout/FormItem.vue';
  import {
    getSingleMainSourceList,
    getMultipleMainSourceList,
    getSourceList,
    getTargetList,
  } from '/@bpmn/config/info';
  import { getMainProcessNodeList, getVariablesSubTableTree, separator } from '/@bpmn/config/info';
  import { CallActivityType, ExecutionType, FinishType, MemberType } from '/@/enums/workflowEnum';
  import { RelationProcessConfig } from '/@/model/workflow/workflowConfig';
  import { TreeProps } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const { showPanel, formInfo } = useStateFormInfo();
  let configInfo: {
    nodeList: Array<NodesConfig>;
    dataOfVariables: TreeProps['treeData'];
    mainSourceList: TreeProps['treeData']; //变量来源 ( 主流程 )
    sourceList: TreeProps['treeData']; //目标变量 ( 主流程 )
    targetList: TreeProps['treeData']; //子流程
  } = reactive({
    nodeList: [],
    dataOfVariables: [],
    mainSourceList: [],
    sourceList: [],
    targetList: [],
  });

  const updateCallActivityExpression = inject('updateCallActivityExpression') as Function;
  const updateCallActivityMulti = inject('updateCallActivityMulti') as Function;

  onMounted(async () => {
    configInfo.nodeList = getMainProcessNodeList();
    let dataOfVariables = getVariablesSubTableTree();
    configInfo.dataOfVariables = dataOfVariables ? dataOfVariables : [];

    if (formInfo.value.callActivityType === CallActivityType.SINGLE) {
      configInfo.mainSourceList = getSingleMainSourceList();
    } else {
      configInfo.mainSourceList = getMultipleMainSourceList();
    }
    configInfo.sourceList = getSourceList();
    if (formInfo.value.schemaId) {
      configInfo.targetList = await getTargetList(formInfo.value.schemaId);
    }
  });
  function changeCallActivityType() {
    if (formInfo.value.callActivityType === CallActivityType.SINGLE) {
      configInfo.mainSourceList = getSingleMainSourceList();
    } else {
      configInfo.mainSourceList = getMultipleMainSourceList();
    }
    formInfo.value.outParams = [];
    formInfo.value.inParams = [];
    updateCallActivityXml();
  }

  //TODO 防抖！！！！
  function updateCallActivityXml() {
    //完成条件如果是单个
    if (formInfo.value.finishType != 2) {
      formInfo.value.percentOf = null;
    }
    updateCallActivityMulti(
      formInfo.value.callActivityType,
      formInfo.value.executionType,
      formInfo.value.finishType,
      formInfo.value.percentOf,
    );
  }
  function selectDataOfVariables(value) {
    let arr = value.split(separator);
    if (arr.length == 3) {
      let nodeId = arr[0];
      let formId = arr[1];
      let formField = arr[2];
      formInfo.value.nodeId = nodeId;
      formInfo.value.formId = formId;
      formInfo.value.formField = formField;
    }
  }
  // 选择流程模板
  async function selectDesign(tempList: Array<RelationProcessConfig>) {
    if (tempList.length == 1) {
      formInfo.value.schemaId = tempList[0].id;
      formInfo.value.schemaName = tempList[0].name;
      configInfo.targetList = await getTargetList(formInfo.value.schemaId);

      updateCallActivityExpression(tempList[0].definitionKey);
    } else {
      formInfo.value.schemaId = '';
      formInfo.value.schemaName = '';
      updateCallActivityExpression();
    }
  }
  // 新增 输入参数
  function addInParamsItem() {
    formInfo.value.inParams.push({
      source: '',
      target: '',
    });
  }
  //删除 输入参数
  function deleteInParamsItem(index: number) {
    formInfo.value.inParams.splice(index, 1);
  }

  // 新增 输出参数
  function addOutParamsItem() {
    formInfo.value.outParams.push({
      source: '',
      target: '',
    });
  }
  //删除 输出参数
  function deleteOutParamsItem(index: number) {
    formInfo.value.outParams.splice(index, 1);
  }

  function percentChange() {
    updateCallActivityMulti(
      formInfo.value.callActivityType,
      formInfo.value.executionType,
      formInfo.value.finishType,
      formInfo.value.percentOf,
    );
  }

  //完成条件设置
  function finishTypeChange() {
    //完成条件如果是单个
    if (formInfo.value.finishType != 2) {
      formInfo.value.percentOf = null;
    }
    updateCallActivityMulti(
      formInfo.value.callActivityType,
      formInfo.value.executionType,
      formInfo.value.finishType,
      formInfo.value.percentOf,
    );
  }
</script>

<style lang="less" scoped>
  .opr-box {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .list {
    .row {
      height: 40px;
      line-height: 30px;
      display: flex;
      justify-content: space-around;
      align-items: center;

      span {
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .common {
        flex-basis: 40%;
      }

      .small {
        flex-basis: 10%;
      }
    }

    .head {
      background-color: #f9f9f9;
    }

    .item {
      border-bottom: 1px solid #f9f9f9;
    }

    .delete-icon {
      color: @clear-color;
    }
  }
</style>
